import { useState, useMemo } from 'react'

function UseMemo4 () {
  const [count, setCount] = useState(100)
  const [theme, setTheme] = useState('pink')

  // 模拟昂贵计算的函数
  const computeExpensiveValue = (count: number) => {
    console.log('昂贵计算的函数执行了')
    // 创建数组长度为 count 的数组，并填充数组的每个元素值为 100
    const numArrs = new Array(count).fill(100)
    // 计算数组中所有元素的和
    return numArrs.reduce((total, item) => total + item, 0)
  }

  // const value = computeExpensiveValue(count)

  // 使用 useMemo 来记忆昂贵计算的结果，来避免重复的执行，从而提升组件的性能
  const value = useMemo(() => computeExpensiveValue(count), [count])

  return (
    <div style={{ backgroundColor: theme, padding: 10 }}>
      <button onClick={() => setTheme(theme === 'pink' ? 'white' : 'pink')}>
        切换主题
      </button>

      <h1>计数器：{count}</h1>
      <button onClick={() => setCount(count + 1)}>+1</button>
      <div>昂贵计算的演示：{value}</div>
    </div>
  )
}

export default UseMemo4
